//
//  ImageHelper.m
//  CarCare
//
//  Created by ileo on 14-9-29.
//  Copyright (c) 2014年 baozun. All rights reserved.
//

#import "ImageHelper.h"

@implementation ImageHelper

+(UIImage *)renderImage:(UIImage *)aImage withColor:(UIColor *)color{
    UIGraphicsBeginImageContextWithOptions(aImage.size, NO, aImage.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, aImage.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGRect rect = CGRectMake(0, 0, aImage.size.width, aImage.size.height);
    CGContextClipToMask(context, rect, aImage.CGImage);
    [color setFill];
    CGContextFillRect(context, rect);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

+(UIImage *)cutImage:(UIImage *)aImage centerSize:(CGSize)size{
    CGRect rect;
    float x,y,w,h;
    if (aImage.size.height <= size.height)
        y = 0,h = aImage.size.height;
    else
        y = aImage.size.height/2 - size.height/2,h = size.height;
    
    if (aImage.size.width <= size.width)
        x = 0,w = aImage.size.width;
    else
        x = aImage.size.width/2 - size.width/2, w = size.width;
    
    rect = CGRectMake(x, y, w, h);
    UIImage *new = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([aImage CGImage], rect)];
    return new;
}

+(UIImage *)cutImage:(UIImage *)aImage rect:(CGRect)rect{
    UIImage *new = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([aImage CGImage], rect)];
    return new;
}

+(UIImage *)imageWithSolidColor:(UIColor *)color size:(CGSize)size{
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

+(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

+(UIImage *)cornerImage:(UIImage *)aImage cornerRadius:(CGFloat)radius{
    UIGraphicsBeginImageContext(aImage.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect rect = CGRectMake(radius, radius, aImage.size.width - radius * 2.0f , aImage.size.height - radius * 2.0f);
    
    CGContextAddEllipseInRect(context, rect);
    CGContextClip(context);
    [aImage drawInRect:rect];

    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newimg;
}
+(UIImage *)watermarkImage:(UIImage *)image withText:(NSString *)text
{
    UIFont * textFont = [UIFont systemFontOfSize:(__MAIN_WIDTH == 320 ? 23 : 25 * __MAIN_RATIO_375)];
    NSDictionary *attributes = @{NSFontAttributeName:textFont};
    CGSize labelSize = [text boundingRectWithSize:CGSizeMake(image.size.width , image.size.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;

    
    UILabel * label = [UILabel labelWithFrame:CGRectMake(0, 0, labelSize.width + 10, labelSize.height + 10) font:textFont text:text textColor:[UIColor whiteColor]];
    label.layer.shadowColor = COLOR_HEXSTRING(@"#4A4A4A").CGColor;
    label.layer.shadowRadius = 5;
    label.layer.shadowOffset = CGSizeMake(0, -1);
    label.layer.shadowOpacity = 1;
    label.textAlignment = NSTextAlignmentRight;
    UIImage * textImage = [ImageHelper imageRenderFromView:label];
    
    UIGraphicsBeginImageContext(image.size);
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    [textImage drawInRect:CGRectMake(image.size.width - label.frame.size.width -  20 * __MAIN_RATIO_375, image.size.height - label.frame.size.height - 15 * __MAIN_RATIO_375, label.frame.size.width, label.frame.size.height)];
    UIImage * resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultImage;
    
    /*
    NSString* mark = text;
    
    int w = image.size.width;
    
    int h = image.size.height;
    
    UIGraphicsBeginImageContext(image.size);
    
    [image drawInRect:CGRectMake(0,0, w, h)];
    
    NSShadow * shadow = [[NSShadow alloc]init];
//    shadow.shadowOffset = CGSizeMake(120, 25);
    shadow.shadowBlurRadius = 116.5;
    shadow.shadowColor = [UIColor redColor];
       NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,  [UIFont fontWithName:@"SnellRoundhand-Bold"size:18],NSFontAttributeName ,shadow,NSShadowAttributeName,nil];
//    NSDictionary *attr = @{
//                           
//                           NSFontAttributeName: [UIFont boldSystemFontOfSize:18],  //设置字体
//                           
//                           NSForegroundColorAttributeName : [Theme mainNavColor ],  //设置字体颜色
//                           
//                           NSShadowAttributeName:shadow
//                           };
    
//    [mark drawInRect:CGRectMake(, , , ) withAttributes:attr];         //左上角
//    [mark drawInRect:CGRectMake(w - , , , ) withAttributes:attr];      //右上角
    [mark drawInRect:CGRectMake(w / 2 - text.length * 5, h - 50 ,text.length * 5 ,30) withAttributes:attr];  //右下角
//    [mark drawInRect:CGRectMake(, h - - , , ) withAttributes:attr];    //左下角
    
    UIImage *aimg = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    */
//    return aimg;

}

+(NSData *)dataWithImage:(UIImage *)aImage compressLength:(CGFloat)length{
    CGFloat quality = 0.8;
    NSData * imgData = UIImageJPEGRepresentation(aImage, quality);
    while (imgData.length > length) {
        quality -= 0.1;
        imgData = UIImageJPEGRepresentation(aImage,quality);
        if (quality <0.2)
            break;
    };
    return imgData;
}

+(UIImage *)imageRenderFromView:(UIView *)aView{
    
    UIGraphicsBeginImageContext(aView.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [aView.layer renderInContext:context];
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

+ (UIImage *) setImage:(UIImage *)image withAlpha:(CGFloat)alpha{
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0f);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, image.size.width, image.size.height);
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);
    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
    CGContextSetAlpha(ctx, alpha);
    CGContextDrawImage(ctx, area, image.CGImage);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

+(NSURLRequest *)requestURLWithURLStr:(NSString *)str{
    NSString *urlStr = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, NULL, kCFStringEncodingUTF8));
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
    return request;
}

#pragma mark - qr

+(UIImage *)qrImageForString:(NSString *)string size:(CGFloat)size{
    return [self createNonInterpolatedUIImageFormCIImage:[self createQRForString:string] withSize:size];
}

+(CIImage *)createQRForString:(NSString *)qrString {
    NSData *stringData = [qrString dataUsingEncoding:NSUTF8StringEncoding];
    // 创建filter
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 设置内容和纠错级别
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    [qrFilter setValue:@"H" forKey:@"inputCorrectionLevel"];
    // 返回CIImage
    return qrFilter.outputImage;
}

+(UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

void ProviderReleaseData (void *info, const void *data, size_t size){
    free((void*)data);
}
+(UIImage*)imageBlackToTransparent:(UIImage*)image withRed:(CGFloat)red andGreen:(CGFloat)green andBlue:(CGFloat)blue{
    const int imageWidth = image.size.width;
    const int imageHeight = image.size.height;
    size_t      bytesPerRow = imageWidth * 4;
    uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,
                                                 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
    CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
    // 遍历像素
    int pixelNum = imageWidth * imageHeight;
    uint32_t* pCurPtr = rgbImageBuf;
    for (int i = 0; i < pixelNum; i++, pCurPtr++){
        if ((*pCurPtr & 0xFFFFFF00) < 0x99999900)    // 将白色变成透明
        {
            // 改成下面的代码，会将图片转成想要的颜色
            uint8_t* ptr = (uint8_t*)pCurPtr;
            ptr[3] = red; //0~255
            ptr[2] = green;
            ptr[1] = blue;
        }
        else
        {
            uint8_t* ptr = (uint8_t*)pCurPtr;
            ptr[0] = 0;
        }
    }
    // 输出图片
    CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, ProviderReleaseData);
    CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, 8, 32, bytesPerRow, colorSpace,
                                        kCGImageAlphaLast | kCGBitmapByteOrder32Little, dataProvider,
                                        NULL, true, kCGRenderingIntentDefault);
    CGDataProviderRelease(dataProvider);
    UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];
    // 清理空间
    CGImageRelease(imageRef);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return resultUIImage;
}

@end
